package com.easy.web.controller;

import com.easy.web.model.User;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 郏高阳 on 2016/8/2.
 */
public class CommonInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);

    /**
     * 拦截器进入，返回true则进入请求Controller
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        logger.info("==============执行顺序: 1、preHandle================");
        String requestUri = request.getRequestURI();
        String method = request.getMethod();
        logger.info("Request:{}  Method:{}",requestUri,method);
        if(requestUri.indexOf("login") > 0){
            return true;
        }
        User user = (User) request.getSession().getAttribute("user");
        String login_time_out = "login_time_out.json";// 配置登录超时接口
        if(user == null && !requestUri.contains(login_time_out)){
            request.getRequestDispatcher(login_time_out).forward(request, response);
            return false;
        }
        return true;
    }

    /**
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
     * 可在modelAndView中加入数据，比如当前时间
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        logger.info("==============执行顺序: 2、postHandle================");
//        if(modelAndView != null){
//            modelAndView.addObject("serverTime", DateUtils.getDate(DateUtils.YYYY_MM_DD_HH_mm_ss));
//        }
    }

    /**
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
     *
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        logger.info("==============执行顺序: 3、afterCompletion================");
    }
}
